package com.uenpay.im.ui.old.activity.contacts;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.adapter.QiYunXinAdapter;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.FriendsRequestManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.entity.UserRequestEntity;
import com.qyx.android.entity.UserRequestStatu;
import com.qyx.android.message.type.PacketType;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import java.util.ArrayList;

/**
 * 新朋友
 *
 * @author SL
 * @created 2016-1-3 上午11:30:58
 * @copyRight http://www.qiyunxin.com
 */

@Route(path = "/im/new_friend")
public class NewFriendsActivity extends BaseActivity {

    private View loading;
    private ListView new_friends_list;
    private FriendListAdapter adapter;// 填充消息列表的adapter
    private FriendsRequestManager mFriendsRequestManager = new FriendsRequestManager();// 好友请求信息管理类
    private UserRequestEntity requestEntity = new UserRequestEntity();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
        IMApplication.config.setIsNewFriend(0);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_list_layout;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
        renderRequest();
    }

    protected void initView() {
        loading = findViewById(R.id.loading);
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.new_friend));
        // ((TextView) findViewById(R.id.title_right_tv)).setText("添加朋友");
        // findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        new_friends_list = (ListView) findViewById(R.id.listview);
    }

    protected void initListener() {
        //返回键点击
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        // listview的长按事件
        new_friends_list
                .setOnItemLongClickListener(new OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> arg0,
                                                   View arg1, int arg2, long arg3) {
                        final UserRequestEntity user = (UserRequestEntity) arg0
                                .getAdapter().getItem(arg2);
                        deleteDialog(user);
                        return true;
                    }
                });
    }

    class FriendListAdapter extends QiYunXinAdapter {
        LayoutInflater inflater;
        ArrayList<UserRequestEntity> _requset;
        // int _width;
        // String type;
        Activity _activity;

        public FriendListAdapter(Activity activity,
                                 ArrayList<UserRequestEntity> requset) {
            inflater = LayoutInflater.from(activity);
            _requset = requset;
            _activity = activity;
        }

        public void setData(ArrayList<UserRequestEntity> requset) {
            _requset = requset;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return _requset.size();
        }

        @Override
        public UserRequestEntity getItem(int arg0) {
            return _requset.get(arg0);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.new_friends_list_item,
                        parent, false);
                holder.userName = (TextView) convertView
                        .findViewById(R.id.request_name);
                holder.userIcon = (RoundImageView) convertView
                        .findViewById(R.id.request_avatar);
                holder.addFriend = (Button) convertView
                        .findViewById(R.id.add_friend);
                holder.added = (TextView) convertView.findViewById(R.id.added);
                holder.content = (TextView) convertView
                        .findViewById(R.id.request_content);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final UserRequestEntity requset = _requset.get(position);
            holder.addFriend.setText(getResources().getString(
                    R.string.accept_friend_apply));
            if (requset.request_status.equals(UserRequestStatu.CREATED)) {
                holder.added.setVisibility(View.GONE);
                holder.addFriend.setVisibility(View.VISIBLE);
            } else {
                holder.added.setVisibility(View.VISIBLE);
                holder.addFriend.setVisibility(View.GONE);

            }

            holder.userName.setText(requset.from_cust_name);// 请求者
            holder.content.setText(requset.content);// 内容
            holder.userIcon.SetUrl(APIConfiguration.getAvatarUrlNormal(
                    requset.from_cust_id + "", PacketType.PERSONAL));

            holder.userIcon.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ActivityHandle.startUserDetailActivity(NewFriendsActivity.this, requset.from_cust_id + "");
                }
            });

            // 确认按钮
            holder.addFriend.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    requestEntity = requset;
                    addToFriend(requset.notice_id);
                }
            });

            return convertView;
        }

        class ViewHolder {
            TextView userName;// 名称
            RoundImageView userIcon;// 用户头像
            Button addFriend;// 确定按钮
            TextView added;// 已经添加
            TextView content;// 请求内容
            TextView friend_school_tv;// 请求者学校
        }
    }

    // 填充list、查询数据
    public void renderRequest() {
        try {
            ArrayList<UserRequestEntity> requests = mFriendsRequestManager
                    .queryAll();
            adapter = new FriendListAdapter(NewFriendsActivity.this, requests);
            new_friends_list.setAdapter(adapter);

        } catch (Exception e) {
            IMApplication.showToast(getResources().getString(
                    R.string.no_new_friends));
        }

    }

    // 确认按钮
    private void addToFriend(final long notice_id) {
        loading.setVisibility(View.VISIBLE);

        ContactsHandle.acceptFriend(notice_id + "",
                new ContactsHandle.IAcceptFriendListener() {

                    @Override
                    public void onAcceptFriendResult(int status, String msg,
                                                     FriendEntity friendEntity) {
                        myHandler.sendEmptyMessage(0);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            // 添加到好友表
                            if (friendEntity != null
                                    && friendEntity.cust_id != null
                                    && !friendEntity.cust_id.equals("")) {
                                FriendDB.updateFriend(friendEntity);
                            }

                            try {
                                // 修改本地数据库数据状态
                                if (requestEntity != null) {
                                    requestEntity.request_status = UserRequestStatu.ACCEPTED;// 接收该同学
                                    mFriendsRequestManager
                                            .updateRequest(requestEntity);
                                }
                                IMApplication.IS_GET_ALL_FRIENDS = true;
                                adapter.setData(mFriendsRequestManager
                                        .queryAll());
                                Intent intent = new Intent(
                                        BroadcastAction.ACTION_AGREE_REQUEST);
                                sendBroadcast(intent);
                                IMApplication
                                        .showToast(R.string.add_friend_succeed);

                            } catch (ParseException e) {
                            }
                        } else if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                        } else {
                            IMApplication
                                    .showToast(R.string.add_friend_failed);
                        }
                    }
                });
    }

    private void deleteDialog(final UserRequestEntity user) {
        String[] delete_text = {IMApplication.getAppContext().getResources()
                .getString(R.string.delete_msg)};// 文本信息

        final MyDialog.Builder dlg = new MyDialog.Builder(this);
        final ListView menus = new ListView(this);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        menus.setLayoutParams(params);
        menus.setTag(delete_text);
        menus.setAdapter(new ArrayAdapter<String>(IMApplication
                .getAppContext(), R.layout.custom_contenxt_menu_item,
                delete_text));

        dlg.setListView(menus);
        dlg.setMessage("");
        if (!TextUtils.isEmpty(user.from_cust_name)) {
            dlg.setTitle(user.from_cust_name);
        } else {
            dlg.setTitle(R.string.action_dialog_title);
        }
        dlg.create().show();

        menus.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position) {
                    case 0:
                        deleteRequset(user._id);
                        break;

                    default:
                        break;
                }
                dlg.getDialog().dismiss();
            }

        });

    }

    private void deleteRequset(int _id) {
        if (mFriendsRequestManager.deleteRequest(_id)) {
            renderRequest();
        } else {
            IMApplication.showToast(getResources().getString(
                    R.string.delete_msg_failed));
        }

    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            }
            return false;
        }
    });

    @Override
    protected void onResume() {
        // 取消所有通知
        IMApplication.notification_sum = 0;
        NotificationManager mNotificationManager = (NotificationManager) IMApplication
                .getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(2);
        adapter.setData(mFriendsRequestManager.queryAll());
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IMApplication.getInstance().removeActivity(this);
    }
}
